package com.Humanities.content.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.base.exception.CommonError;
import com.xuecheng.base.exception.XueChengPlusException;
import com.Humanities.content.config.MultipartSupportConfig;
import com.Humanities.content.feignclient.MediaServiceClient;
import com.Humanities.content.mapper.CourseBaseMapper;
import com.Humanities.content.mapper.CourseMarketMapper;
import com.Humanities.content.mapper.CoursePublishMapper;
import com.Humanities.content.mapper.CoursePublishPreMapper;
import com.xuecheng.content.model.dto.CourseBaseInfoDto;
import com.xuecheng.content.model.dto.CoursePreviewDto;
import com.xuecheng.content.model.dto.TeachplanDto;
import com.xuecheng.content.model.po.CourseBase;
import com.xuecheng.content.model.po.CourseMarket;
import com.xuecheng.content.model.po.CoursePublish;
import com.xuecheng.content.model.po.CoursePublishPre;
import com.Humanities.content.service.ICourseBaseService;
import com.Humanities.content.service.ICoursePublishService;
import com.Humanities.content.service.ITeachplanService;
import com.xuecheng.messagesdk.model.po.MqMessage;
import com.xuecheng.messagesdk.service.MqMessageService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.Builder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 课程发布 服务实现类
 * </p>
 *
 * @author ysj
 * @since 2025-03-26
 */

//课程发布相关接口实现
@Slf4j
@Service
public class CoursePublishServiceImpl extends ServiceImpl<CoursePublishMapper, CoursePublish> implements ICoursePublishService {
    @Autowired
    ICourseBaseService courseBaseInfoService;

    @Autowired
    ITeachplanService teachplanService;

    @Autowired
    CourseMarketMapper courseMarketMapper;
    @Autowired
    CoursePublishPreMapper coursePublishPreMapper;
    @Autowired
    CourseBaseMapper courseBaseMapper;
    @Autowired
    CoursePublishMapper coursePublishMapper;
    @Autowired
    MqMessageService mqMessageService;
    @Autowired
    MediaServiceClient mediaServiceClient;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RedissonClient redissonClient;

    @Override
    public CoursePreviewDto getCoursePreviewInfo(Long courseId) {

        //课程基本信息、营销信息
        CourseBaseInfoDto courseBaseInfo = courseBaseInfoService.getCourseBaseInfo(courseId);

        //课程计划信息
        List<TeachplanDto> teachplanTree= teachplanService.findTeachplanTree(courseId);

        CoursePreviewDto coursePreviewDto = new CoursePreviewDto();
        coursePreviewDto.setCourseBase(courseBaseInfo);
        coursePreviewDto.setTeachplans(teachplanTree);
        return coursePreviewDto;
    }
    @Transactional
    @Override
    public void commitAudit(Long companyId, Long courseId) {
        //课程信息
        CourseBaseInfoDto courseBaseInfo = courseBaseInfoService.getCourseBaseInfo(courseId);


        if (courseBaseInfo == null) {
            log.error("课程不存在，课程id:{}", courseId);
            XueChengPlusException.cast("课程不存在");

        }
        //本机构只允许提交本机构的课程
        if(!courseBaseInfo.getCompanyId().equals(companyId)){
            XueChengPlusException.cast("不允许提交其它机构的课程。");
        }
        //是否上次了图片
        if (courseBaseInfo.getPic() == null || courseBaseInfo.getPic().isEmpty()) {
            log.error("课程图片未上传，课程id:{}", courseId);
            XueChengPlusException.cast("课程图片未上传");

        }
        //判断课程是否已经发布
        if (courseBaseInfo.getStatus().equals("202004")) {
            log.error("课程已经审核通过，课程id:{}", courseId);
            XueChengPlusException.cast("课程已经审核通过");

        }
        //判断课程是否已经提交审核
        if (courseBaseInfo.getStatus().equals("202003")) {
            log.error("课程已经提交审核，课程id:{}", courseId);
            XueChengPlusException.cast("课程已经提交审核");

        }
        //判断是否有课程计划
        List<TeachplanDto> teachplanTree = teachplanService.findTeachplanTree(courseId);
        if(teachplanTree.size() == 0){
            log.error("课程计划未添加，课程id:{}", courseId);
            XueChengPlusException.cast("课程计划未添加");
        }
        CoursePublishPre coursePublishPre = new CoursePublishPre();
        BeanUtil.copyProperties(courseBaseInfo, coursePublishPre);
        //teachplanTree转成json字符串
        String teachplanJson = JSON.toJSONString(teachplanTree);
        coursePublishPre.setTeachplan(teachplanJson);
        //课程营销信息
        CourseMarket courseMarket = courseMarketMapper.selectById(courseId);
        //转为json
        String courseMarketJson = JSON.toJSONString(courseMarket);
        //将课程营销信息json数据放入课程预发布表
        coursePublishPre.setMarket(courseMarketJson);
        //设置预发布记录状态,已提交
        coursePublishPre.setStatus("202003");
        //教学机构id
        coursePublishPre.setCompanyId(companyId);
        //提交时间
        coursePublishPre.setCreateDate(LocalDateTime.now());
        coursePublishPre.setId(courseId);
        CoursePublishPre coursePublishPreUpdate = coursePublishPreMapper.selectById(courseId);
        if(coursePublishPreUpdate == null){
            //添加课程预发布记录
            coursePublishPreMapper.insert(coursePublishPre);
        }else{
            coursePublishPreMapper.updateById(coursePublishPre);
        }

        //更新课程基本表的审核状态
        CourseBase courseBase = courseBaseMapper.selectById(courseId);
        courseBase.setStatus("202003");
        courseBase.setChangeDate(LocalDateTime.now());
        courseBaseMapper.updateById(courseBase);


    }

    /**
     * 课程发布
     * @param companyId
     * @param courseId 课程id
     */
    @Transactional
    @Override
    public void publishCourse(Long companyId, Long courseId) {
        //约束校验
        //查询课程预发布表
        CoursePublishPre coursePublishPre = coursePublishPreMapper.selectById(courseId);
        if(coursePublishPre == null){
            XueChengPlusException.cast("请先提交课程审核，审核通过才可以发布");
        }
        //本机构只允许提交本机构的课程
        if(!coursePublishPre.getCompanyId().equals(companyId)){
            XueChengPlusException.cast("不允许提交其它机构的课程。");
        }


        //课程审核状态
        String auditStatus = coursePublishPre.getStatus();
        //审核通过方可发布
        if(!"202004".equals(auditStatus)){
            XueChengPlusException.cast("操作失败，课程审核通过方可发布。");
        }


        //保存课程发布信息
        saveCoursePublish(courseId);

        //保存消息表
        saveCoursePublishMessage(courseId);


        //删除课程预发布表对应记录
        coursePublishPreMapper.deleteById(courseId);

    }

    /**
     * 生成课程静态化文件
     * @param courseId  课程id
     * @return
     */
    @Override
    public File generateCourseHtml(Long courseId) {

        //静态化文件
        File htmlFile  = null;

        try {
            //配置freemarker
            Configuration configuration = new Configuration(Configuration.getVersion());

            //加载模板
            //选指定模板路径,classpath下templates下
            //得到classpath路径
            String classpath = this.getClass().getResource("/").getPath();
            configuration.setDirectoryForTemplateLoading(new File(classpath + "/templates/"));
            //设置字符编码
            configuration.setDefaultEncoding("utf-8");

            //指定模板文件名称
            Template template = configuration.getTemplate("course_template.ftl");

            //准备数据
            CoursePreviewDto coursePreviewInfo = this.getCoursePreviewInfo(courseId);

            Map<String, Object> map = new HashMap<>();
            map.put("model", coursePreviewInfo);

            //静态化
            //参数1：模板，参数2：数据模型
            String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
            System.out.println(content);
            //将静态化内容输出到文件中
            InputStream inputStream = IOUtils.toInputStream(content);
            //创建静态化文件
            htmlFile = File.createTempFile("course",".html");
            log.debug("课程静态化，生成静态文件:{}",htmlFile.getAbsolutePath());
            //输出流
            FileOutputStream outputStream = new FileOutputStream(htmlFile);
            IOUtils.copy(inputStream, outputStream);
        } catch (Exception e) {
            log.error("课程静态化异常:{}",e.toString());
            XueChengPlusException.cast("课程静态化异常");
        }

        return htmlFile;
    }

    /**
     * 上传课程静态化文件
     * @param courseId
     * @param file  静态化文件
     */
    @Override
    public void uploadCourseHtml(Long courseId, File file) {
        MultipartFile multipartFile = MultipartSupportConfig.getMultipartFile(file);
        String course = mediaServiceClient.uploadFile(multipartFile, "course/"+courseId+".html");
        if(course==null){
            XueChengPlusException.cast("上传静态文件异常");
        }
    }

    private void saveCoursePublishMessage(Long courseId) {
        //向消息表写入数据
        MqMessage mqMessage = mqMessageService.addMessage("course_publish", String.valueOf(courseId), null, null);
        if(mqMessage==null){
            XueChengPlusException.cast(CommonError.UNKOWN_ERROR);
        }
    }

    private void saveCoursePublish(Long courseId) {
        //把课程预发布表的数据拷贝到课程发布表
        CoursePublishPre coursePublishPre = coursePublishPreMapper.selectById(courseId);
        CoursePublish coursePublish = BeanUtil.toBean(coursePublishPre, CoursePublish.class);
        //设置课程发布状态
        coursePublish.setStatus("203002");
        CoursePublish coursePublishUpdate = coursePublishMapper.selectById(courseId);
        if(coursePublishUpdate == null){
            coursePublishMapper.insert(coursePublish);
        }else{
            coursePublishMapper.updateById(coursePublish);
        }
        //更新课程基本表的发布状态
        CourseBase courseBase = courseBaseMapper.selectById(courseId);
        LambdaUpdateWrapper<CourseBase> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(CourseBase::getId, courseId);
        updateWrapper.set(CourseBase::getStatus, "203002");
        updateWrapper.set(CourseBase::getChangeDate, LocalDateTime.now());
        courseBaseMapper.update(courseBase, updateWrapper);
    }
    /**
     * 查询课程发布信息
     */
    public CoursePublish getCoursePublish(Long courseId){
        CoursePublish coursePublish = coursePublishMapper.selectById(courseId);
        return coursePublish ;
    }

//    /**
//     * 查询缓存中的课程信息
//     * @param courseId
//     * @return
//     */
//    @Override
//    public CoursePublish getCoursePublishCache(Long courseId) {
//        //查询缓存
//        Object  jsonObj = stringRedisTemplate.opsForValue().get("course:" + courseId);
//        if(jsonObj != null){
//            //将json字符串转换为CoursePublish对象
//            System.out.println("=================从缓存查=================");
//            String jsonStr = (String) jsonObj;
//            if(jsonStr.equals("null")){
//                return null;
//            }
//            CoursePublish coursePublish = JSON.parseObject(jsonStr, CoursePublish.class);
//            return coursePublish;
//        }else {
//            synchronized (this) {  //双重检查锁定，防止缓存击穿
//                //再次查询缓存，防止缓存击穿
//                Object jsonObj2 = stringRedisTemplate.opsForValue().get("course:" + courseId);
//                if (jsonObj2 != null) {
//                    String jsonStr = (String) jsonObj2;
//                    if(jsonStr.equals("null")){
//                        return null;
//                    }
//                    CoursePublish coursePublish = JSON.parseObject(jsonStr, CoursePublish.class);
//                    return coursePublish;
//                }
//                //缓存中没有数据，从数据库查询
//                CoursePublish coursePublish = this.getCoursePublish(courseId);
//
//                //将课程发布信息放入缓存
//                System.out.println("从数据库查询...");
//                String jsonStr = JSON.toJSONString(coursePublish); //对象转换为JSON字符串
//                stringRedisTemplate.opsForValue().set("course:" + courseId, jsonStr,30+new Random().nextInt(100), TimeUnit.SECONDS); //设置过期时间300秒
//                //解决缓存雪崩+穿透问题，给缓存在30秒的基础上设置随机过期时间
//
//                return coursePublish;
//            }
//
//        }
//
//    }    没有使用分布式锁

    /**
     * 查询缓存中的课程信息
     * @param courseId
     * @return
     */
    //与上面方法不同的是使用了redisson分布式锁
    @Override
    public CoursePublish getCoursePublishCache(Long courseId) {
        //查询缓存
        Object  jsonObj = stringRedisTemplate.opsForValue().get("course:" + courseId);
        if(jsonObj != null){
            //将json字符串转换为CoursePublish对象
            System.out.println("=================从缓存查=================");
            String jsonStr = (String) jsonObj;
            if(jsonStr.equals("null")){
                return null;
            }
            CoursePublish coursePublish = JSON.parseObject(jsonStr, CoursePublish.class);
            return coursePublish;
        }else {
            //使用redisson分布式锁
            RLock lock = redissonClient.getLock("course:lock:" + courseId);//每门课程设置一个锁
            lock.lock(); //加锁
            try{
                //再次查询缓存，防止缓存击穿
                Object jsonObj2 = stringRedisTemplate.opsForValue().get("course:" + courseId);
                if (jsonObj2 != null) {
                    String jsonStr = (String) jsonObj2;
                    if(jsonStr.equals("null")){
                        return null;
                    }
                    CoursePublish coursePublish = JSON.parseObject(jsonStr, CoursePublish.class);
                    return coursePublish;
                }
                //将课程发布信息放入缓存
                System.out.println("...从数据库查询...");
                //缓存中没有数据，从数据库查询
                CoursePublish coursePublish = this.getCoursePublish(courseId);

                String jsonStr = JSON.toJSONString(coursePublish); //对象转换为JSON字符串
                stringRedisTemplate.opsForValue().set("course:" + courseId, jsonStr,30+new Random().nextInt(100), TimeUnit.SECONDS); //设置过期时间300秒
                //解决缓存雪崩+穿透问题，给缓存在30秒的基础上设置随机过期时间

                return coursePublish;
            }finally {
                lock.unlock(); //释放锁
                log.debug("释放锁，课程id:{}", courseId);
            }

            }

        }



}
